package com.starinside.wp.controller.api;

import com.starinside.wp.domain.Children;
import com.starinside.wp.domain.FamilyFeed;
import com.starinside.wp.domain.Feeds;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.foundation.constant.FeedConstant;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.foundation.vo.ChildrenVo;
import com.starinside.wp.foundation.vo.FeedsVO;
import com.starinside.wp.foundation.vo.WxParent;
import com.starinside.wp.repository.ChildrenRepository;
import com.starinside.wp.repository.FeedsRepository;
import com.starinside.wp.repository.WxParentRepository;
import com.starinside.wp.service.BindedBabyService;
import com.starinside.wp.service.FeedsService;
import com.starinside.wp.service.UploadService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SignedObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * @Describle This Class Is
 * @Author ZengMin
 * @Date 2018/11/7 10:08
 * @Company Matt
 */
@RequestMapping("/wx/api/feed")
@RestController
@Api(value ="/wx/api/feed", tags = "宝宝时光轴（新）")
public class APIFeedController {

    @Value("${teach.server.url}")
    String teachUrl;

    @Autowired
    FeedsService feedsService;

    @Autowired
    BindedBabyService bindedBabyService;

    @Autowired
    private UploadService uploadService;


    @RequestMapping(value = "/getFeedList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户关联所有宝宝的时光轴", notes = "多个images和video用‘|’隔开；type:类型 1晨检签到2观测记录3托班月评4排课通知5课堂评测6SAT月评7生日会； isPraises=true表示当前用户已赞")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "分页下标"),
            @ApiImplicitParam(name = "pageSize", value = "页容量")
    })
    public StatusResponse getFeedList(HttpServletRequest req, HttpServletResponse resp,
                                      PagerQuery pagerQuery) {
        //先取此用户基本信息
        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        //取此用户下所有孩子的id
        List<BindedBabyVO> list = bindedBabyService.getAllBindedBabyByParent(loginUser.getParentId());

        return StatusResponse.success(feedsService.getAllByChildrens(list, pagerQuery, loginUser.getParentId()));
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户关联所有宝宝的时光轴条目对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "feedId", value = "条目 id"),
    })
    public StatusResponse detail(HttpServletRequest req, HttpServletResponse resp,
                                 String feedId){
        //先取此用户基本信息
        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");
        Feeds f = feedsService.getOne(feedId);
        return StatusResponse.success(FeedsVO.of(f));
    }


    @RequestMapping(value = "/link_detail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户关联所有宝宝的时光轴条目关联对象详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "feedId", value = "条目 id"),
            @ApiImplicitParam(name = "pageNum", value = "分页下标"),
            @ApiImplicitParam(name = "pageSize", value = "页容量")
    })
    public StatusResponse linkDetail(HttpServletRequest req, HttpServletResponse resp,
                                     String feedId, PagerQuery pagerQuery){

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        String childrenId = loginUser.getDefaultBabyId();


        //
        Map feedDetail = feedsService.getOne(feedId, loginUser.getParentId());

        //
        Object linkedObjects = feedsService.getLinkedObjects(feedId, childrenId, pagerQuery);

        feedDetail.put("linkedObjects", linkedObjects);

        return StatusResponse.success(feedDetail);
    }


    @RequestMapping(value = "/praise", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("点赞/取消赞")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "feedId", value = "动态Id"),
            @ApiImplicitParam(name = "type", value = "类型 1点赞 2取消赞")
    })
    public StatusResponse addPraise(HttpServletRequest req, HttpServletResponse resp,
                                    @RequestParam(required = true) String feedId,
                                    @RequestParam(required = true) int type){
        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");
        String userId = loginUser.getParentId();

        switch (type){
            case FeedConstant.ADD_PRAISE:
                boolean b = feedsService.addPraise(userId, feedId);
                return StatusResponse.success(b);
            case FeedConstant.DEL_PRAISE:
                boolean del = feedsService.deletePraise(userId, feedId);
                return StatusResponse.success(del);
        }
        return StatusResponse.error(ErrorCode.SIGN_ERROR,"参数有误！");
    }

    //课表
    @RequestMapping(value = "/detail_plan_course", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "动态详情", notes = "type=4 || type=6 时 linkId为动态详情页面的URL")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "分页下标"),
            @ApiImplicitParam(name = "pageSize", value = "页容量")
    })
    public StatusResponse getDetailPlanCourse(HttpServletRequest req, PagerQuery pagerQuery) throws IOException {

        WxUser user = (WxUser) req.getSession().getAttribute("loginUser");

        if(StringUtils.isEmpty(user.getParentId()) || StringUtils.isEmpty(user.getDefaultBabyId()) || StringUtils.isEmpty(user.getParentMobile())){
            return StatusResponse.error(ErrorCode.CHILDREN_NOT_EXIST,"当前账号下没有宝宝信息");
        }

        String childrenId = user.getDefaultBabyId();

        Object result = feedsService.getDetailPlanCourse(childrenId,pagerQuery);
        return StatusResponse.success(result);
    }

    //评测
    @RequestMapping(value = "/detail_evaluate", method = RequestMethod.GET)
    @ApiOperation("动态详情_评测信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "linkId", value = "动态关联id")
    })
    @ResponseBody
    public StatusResponse getDetailEvaluate(String linkId) throws IOException {
        Object result = feedsService.getDetailEvaluate(linkId);
        return StatusResponse.success(result);
    }

    // 发布班级圈
    @RequestMapping(value = "/post_plain", method = RequestMethod.POST, headers="content-type=multipart/form-data")
    @ApiOperation("家长发时光轴")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题"),
            @ApiImplicitParam(name = "content", value = "内容"),
            @ApiImplicitParam(name = "mediaType", value = "媒体类型，0图片，1视频"),
            @ApiImplicitParam(name = "childrenId", value = "当指定宝宝时，关联指定宝宝，否则关联默认宝宝"),
    })
    @ResponseBody
    public StatusResponse postFeed(HttpServletRequest req, String title, String content,
                                   String resourceUrl,
                                   Integer mediaType, String childrenId) throws IOException {

        WxUser user = (WxUser) req.getSession().getAttribute("loginUser");
        String wxUserId = user.getOpenidWp();

        String cid = StringUtils.isEmpty(childrenId )? user.getDefaultBabyId(): childrenId;

        feedsService.postFeeds(user.getParentId(), cid, title, content, resourceUrl, mediaType);

        return StatusResponse.success(null);
    }

    // 发布班级圈
    @RequestMapping(value = "/post", method = RequestMethod.POST, headers="content-type=multipart/form-data")
    @ApiOperation("家长发时光轴")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题"),
            @ApiImplicitParam(name = "content", value = "内容"),
            @ApiImplicitParam(name = "mediaType", value = "媒体类型，0图片，1视频"),
            @ApiImplicitParam(name = "childrenId", value = "当指定宝宝时，关联指定宝宝，否则关联默认宝宝"),
    })
    @ResponseBody
    public StatusResponse postFeed(HttpServletRequest req, String title, String content,
                                   @ApiParam(value="上传的文件，数组", allowMultiple = true) MultipartFile[] files,
                                   Integer mediaType, String childrenId) throws IOException {

        WxUser user = (WxUser) req.getSession().getAttribute("loginUser");
        String wxUserId = user.getOpenidWp();

        String resourceUrl = "";
        if(files != null && files.length > 0){
            if(mediaType == 0){
                resourceUrl =  uploadService.uploadFamilyRecordImg(wxUserId, files);
            }else if(mediaType == 1){
                resourceUrl =  uploadService.uploadFamilyRecordVideo(wxUserId, files);
            }
        }

        String cid = StringUtils.isEmpty(childrenId )? user.getDefaultBabyId(): childrenId;

        feedsService.postFeeds(user.getParentId(), cid, title, content, resourceUrl, mediaType);

        return StatusResponse.success(null);
    }
}
